package com.jeeplus.modules.api.utils;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
@Aspect
@Order(1)
public class TokenValidateImpl extends BaseController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    private JwtUtils jwtUtils;

    @Pointcut("@annotation(com.jeeplus.modules.annotation.TokenValidate)")
    public void pointMethod() {
    }

    @Around("pointMethod()")
    public Object aroundTokenValidate(ProceedingJoinPoint joinPoint) {
        AjaxJson ajaxJson = new AjaxJson();
        String name = joinPoint.getSignature().getName();
        log.info("目标方法:{}的token验证器", name);
        String header = request.getHeader(jwtHeaderName);
        if (StringUtils.isNotEmpty(header)) {
            log.info("获取到请求头信息：{}", header);
            String s = jwtUtils.validateTokenAndGetClaims(header);
            if (s.equals("过期")) {
                ajaxJson.setMsg("登录过期");
                ajaxJson.setCode(2);
                return ajaxJson;
            }
            try {
                Object proceed = joinPoint.proceed();
                log.info("方法执行完毕,返回值为：{}", proceed);
                return proceed;
            } catch (Throwable throwable) {
                log.info("方法执行出现异常:{}", throwable.getMessage());
                ajaxJson.setMsg("验证出现异常,无法通过验证!");
                return ajaxJson;
            }
        } else {
            ajaxJson.setMsg("请求头为空,无法通过验证");
            return ajaxJson;
        }
    }
}
